package com.azt.provider.impl;

import com.azt.api.enums.UserEnum;
import com.azt.api.pojo.*;
import com.azt.api.service.CompanyService;
import com.azt.api.service.FunctionService;
import com.azt.api.service.UserPermissionService;
import com.azt.api.service.UserService;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.CompanyMapper;
import com.azt.provider.mapper.RoleMapper;
import com.azt.provider.mapper.UserRoleMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@Transactional
public class UserPermissionServiceImpl  implements UserPermissionService {

	@Autowired
	private FunctionService functionService;
	@Autowired
    private UserService userService;
	@Autowired
	private UserRoleMapper userRoleMapper;	
	@Autowired
	private RoleMapper roleMapper;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyMapper companyMapper;
	@Override
	public Role getRoleById(Integer roleid) {
		return roleMapper.getRoleById(roleid);
	}

	@Override
	public void updateRole(Role roleById) {
		roleMapper.updateByPrimaryKey(roleById);
	}

	@Override
	public void saveRole(Role role) {
		roleMapper.insert(role);
	}

	@Override
	public boolean hasThisPerm(int roleId, String[] codes, int type) {
		if(ArrayUtil.isNotEmpty(codes) && (type == 1 || type == 2)) {
			if(userRoleMapper.hasThisPerm(roleId, codes, type) > 0) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public Pagination getRoleModelByPage(int pageNo, int pageSize, Map<String, String> searchMap) {
		String so_urole = searchMap.get("so_urole");
		Map param=new HashMap();
		if(StringUtils.isNotBlank(so_urole)){
			param.put("name", so_urole);
		}
		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		List<Role> rolelist=roleMapper.searchRole(param);
		
		Pagination pagination = new Pagination(startPage, rolelist);
		pagination.setList(rolelist);
		pagination.setParams(searchMap);
		return pagination;
	}
	
	@Override
	public void deleteRole(Role role) {
		if(role != null) {
			roleMapper.delete(role);
		}
	}


	@Override
	public List<Role> getRoleByRoleType(int roletype) {
		Role role = new Role();
		role.setRoleType(roletype);
		return roleMapper.select(role);
	}

	@Override
	public List<Role> findRoleByUserId(int userId) {
		return roleMapper.findRoleByUserId(userId);
	}


	@Override
	public boolean ifProviderRole(int userId) {
		List<Role> roleByUserId = findRoleByUserId(userId);
		if (CollectionUtil.isNotEmpty(roleByUserId)) {
			for (Role role : roleByUserId) {
				if (role.getRoleType().compareTo(2) == 0) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public List<Role> getAllRole() {
		return roleMapper.getAllRole();
	}

	//获取默认管理员除了领导
	@Override
	public List<Role> getIfAdminRole() {
		List<Role> adminroles=new ArrayList<Role>();
		List<Role> allRole = this.getAllRole();
		if(allRole!=null && allRole.size()>0){
			for(Role ar:allRole){
				if(ar.getCode().equals("cadmin") || ar.getCode().equals("padmin")){
					adminroles.add(ar);
				}
			}
		}
		return adminroles;
	}
	@Override
	public List<Role> getRoleByCompanyId(Integer companyId) {
		List<Role> companyCreateList= roleMapper.getRoleByCompanyId(companyId);
		Company c=companyMapper.selectByPrimaryKey(companyId);
		if(!c.getIsprovider().equals(0) || !c.getIspurchaser().equals(0)){
			Role r=new Role();
			r.setIfAdmin(1);
			r.setIfDefault(1);
			if(c.getIsprovider().equals(1)&&c.getIspurchaser().equals(0)){
				r.setRoleType(2);
			}
			if(c.getIsprovider().equals(0)&&c.getIspurchaser().equals(1)){
				r.setRoleType(1);
			}
			List<Role> adminList=roleMapper.select(r);
			for (int i = 0; i < adminList.size(); i++) {
				companyCreateList.add(adminList.get(i));
			}
			
		}
		return companyCreateList;
	}

	@Override
	public List<Role> findRoleNotAdmin(int companyId) {
		Role role = new Role();
		role.setRemoved(0);
		role.setIfAdmin(0);
		role.setCompanyId(companyId);
		Example example = new Example(Role.class);
		example.createCriteria().andEqualTo(role);
		example.orderBy("sortNum").asc();
		return roleMapper.selectByExample(example);
	}
	
	@Override
	public Role getRoleByCode(String code) {
		Role role = new Role();
		role.setCode(code);
		return roleMapper.selectOne(role);
	}

	@Override
	public List<Role> getRoleByCompanyIdType(Integer companyId, Integer RoleType) {
		return roleMapper.getRoleByCompanyIdType(companyId,RoleType);
	}
	
	@Override
	public void insertUserRole(int userId, int roleId) {
		UserRole userRole = new UserRole();
		userRole.setUserId(userId);
		userRole.setRoleId(roleId);
		userRole.setCreatetime(new Date());
		userRoleMapper.insertSelective(userRole);
	}

	@Override
	public UserRole getUserRoleById(Integer id) {
		return userRoleMapper.getUserRoleById(id);
	}

	@Override
	public UserRole getUserRoleByRoleId(Integer roleId,Integer userId) {
		return userRoleMapper.getUserRoleByRoleId(roleId,userId);
	}
	
	@Override
	public List<UserRole> getUserRolesByRoleId(Integer roleId) {
		return userRoleMapper.getUserRolesByRoleId(roleId);
	}
	@Override
	public List<UserRole> getUserRoleByAdmin(Integer companyId, List<Role> ifAdminRole) {
		return userRoleMapper.getUserRoleByAdmin(companyId,ifAdminRole);
	}
	@Override
	public void saveUserRole(UserRole userRole) {
		userRoleMapper.insertSelective(userRole);
	}
	public void deleteUserRole(UserRole userRole) {
		if(userRole != null) {
			userRoleMapper.delete(userRole);
		}
	}

	
	@Override
	public Boolean TestUserFunction(Integer userId, Integer roleType, Integer funcId) {
		Map<String, Object> ParameterMap = new HashMap<String, Object>();
		ParameterMap.put("id", funcId);
		List<Authority> authoritys = functionService.getAuthorityByUserIdAndFunc(userId, roleType, ParameterMap);
		if (authoritys != null && authoritys.size() > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public void ReviewedUserRole(Integer companyId) {
		Company company = companyService.getCompanyById(companyId);
		List<Role> allDefautRole= this.getAllRole();
		List<UserRole> userRole = this.getUserRoleByAdmin(companyId, allDefautRole);
		
		if(userRole!=null && userRole.size()==1){//只有一条数据是 注册用户  删除
			User user= userService.getUserById(userRole.get(0).getUserId());
			this.deleteUserRole(userRole.get(0));
			//拿到默认的管理员
			 List<Role> ifAdminRole= getIfAdminRole();
			 //创建新的userrole
			if (company != null) {
				// 采购商
				if (company.getIspurchaser() == 1) {
					if (ifAdminRole != null && ifAdminRole.size() > 0) {
						for (Role rl : ifAdminRole) {
							if (rl.getRoleType() == 1) {// 采购商
								createUserRole(rl, user);
							}
						}
					}

				}
				// 供应商
				if (company.getIsprovider() == 1) {
					if (ifAdminRole != null && ifAdminRole.size() > 0) {
						for (Role rl : ifAdminRole) {
							if (rl.getRoleType() == 2) {// 供应商
								createUserRole(rl, user);
							}
						}
					}
				}
			}
		}
	}
	    
	

	@Override
	public void createUserRole(Role newRole, User user) {
		UserRole ur = new UserRole();
		ur.setRoleId(newRole.getId());
		ur.setUserId(user.getId());
		this.saveUserRole(ur);
	}


	@Override
	public List<Role> getRoleByParameter(Map parameter) {
		return roleMapper.getRoleByParameter(parameter);
	}

	@Override
	public List<Role> getNonDefaultRoles(List<Role> roles) {
		List<Role> NonDefaultRoles=new ArrayList<Role>();
		if(roles!=null && roles.size()>0){
			for(Role role:roles){
				if(role.getIfDefault()!=1){
					NonDefaultRoles.add(role);
				}
			}
		}
		return NonDefaultRoles;
	}

	
	@Override
	public void saveOrUpdateRoleAuthority(Company company, Map<String, Object> parseMap, Role role) {
		Map<String, String[]> functionMap = (Map<String, String[]>) parseMap.get("parent");
		role.setCompanyId(company.getId());
		if(role.getId()!=null){
			this.updateRole(role);
		}else{
			this.saveRole(role);
		}
		
		functionService.delAuthorityByRoleId(role.getId());
		// 创建分公司权限菜单
		functionService.createBranchAuthority(role.getId(), functionMap);
		
	}

	@Override
	public Pagination searchNotDefaultRoles(int pageNo, int pageSize, Integer companyId, Integer roleType) {
		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		List<Role> RoleByCompany = this.getRoleByCompanyIdType(companyId,roleType);
		List<Role> notDefaultRoles =new ArrayList();
		 if(RoleByCompany!=null && RoleByCompany.size()>0){
			 //展示
			 for(Role rl:RoleByCompany){
				 if(rl.getIfAdmin()==0){
					 List<UserRole> userRoles = this.getUserRolesByRoleId(rl.getId());
					 List<User> users = userService.getUsersByUserRoles(userRoles);
					 rl.setUsers(users);
					 notDefaultRoles.add(rl);
				 }
			 }
		 }
		Pagination pagination = new Pagination(startPage, notDefaultRoles);
		pagination.setList(notDefaultRoles);
		return pagination;
	}

	@Override
	public Role quitCompany(User user, List<Role> role) {
	    user.setCompanyId(null);
	    user.setCompany(null);
		userService.saveOrUpdate(user);
		//删除userrole 建立注册用户的角色
		if(role!=null && role.size()>0){
			for(Role rl:role){
				UserRole  userRole= this.getUserRoleByRoleId(rl.getId(), user.getId());
				//删除老的userrole关系
				this.deleteUserRole(userRole);
			}
		}
	
	
		Role newrole = this.getRoleByCode("register");
		//创建新的userrole
		this.createUserRole(newrole, user);
		return newrole;
		
	}


}
